<?php

namespace App\Listeners;
use App\Constant\QueueKey;
use App\Constant\RepayConstant;
use App\Events\CollectionReceiptEvent;
use App\Events\WithHoldEvent;
use App\Facades\CollectionRequestFacade;
use App\Facades\CommonPlatformRequestFacade;
use App\Models\CollectionApiRequest;
use App\Models\RepayRecord;
use App\Models\Traits\RepaySummary;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use App\Events\RepayMentEvent;
use App\Events\ActiveDeductionEvent;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;

class WithHoldEventListener implements  ShouldQueue
{
    use InteractsWithQueue;
    public $connection = 'redis';

    public $queue = QueueKey::QUEUE_COLLECTION_RECEIPT;

    const NOTIFY_TYPE_ONE=1;//代扣申请反馈
    const NOTIFY_TYPE_TWO=2;//销账申请反馈
    const NOTIFY_TYPE_THREE=3;//提前结清反馈
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        $caseCode = $event->caseCode;
        $type = $event->type;
        $apply_number=$event->applyNumber;;
        $status=$event->state;
        switch ($type) {
            case
            RepayConstant::COLLECTION_BACK_TYPE_ONE:
                $message = '代扣申请';
            case
            RepayConstant::COLLECTION_BACK_TYPE_TWO:
                $message = '销账申请';
            case
            RepayConstant::COLLECTION_BACK_TYPE_THREE:
                $message = '提前结清申请';
            default:
                $message = '';
        }
        $responseData = [
            'caseCode' => $caseCode,
            'type' => $type,
            'applyNumber' => $apply_number,
            'state' => $status,
            'message' =>$message,
        ];
        //如果是催收那边发起的,回执一下
        try{
            $collectionData = CollectionApiRequest::where('response_code',CollectionApiRequest::RESPONSE_OK)
                ->where('apply_number',$apply_number)
                ->first();
            $result = CollectionRequestFacade::sendReceipt($responseData);
            $data=$this->saveReceiptData($collectionData->id,$result);
        }catch (\Exception $e){
            \Log::debug($e->getMessage());
        }
        return;
    }
    /*
     * 回执
     * $recordInfo model对象
     * $api_type int api类型
     * $status 1 响应成功 2 回执成功 3部分成功部分失败
     */

    public function sendData(RepayRecord $recordInfo,$api_type,$status){
        $summaryInfo = \App\Models\Collection\RepaySummary::select(['loan_id','id','data_type','trans_id'])->where('id',$recordInfo->summary_id)->first();
        $responseData = [
            'caseCode' => $summaryInfo->getCaseCode(),
            'type' => $api_type,
            'applyNumber' => $recordInfo->apply_number,
            'statue' => $status,
            'message' =>$recordInfo->status==RepayRecord::STATUS_THREE?$recordInfo->failure_message:'',
        ];
        return $responseData;
    }

    /**
     * Description:对回执的响应进行处理
     * Author:zlk
     * @param $collection_id integer collection_api_request表的id
     * @param $result 回执响应数据
     */
    private function saveReceiptData($collection_id,$result){
        if(isset($result['resultData'])){
            $receipt_response_code = isset($result['resultData']['result']) ? $result['resultData']['result'] : 0;
            $updateData = [
                'receipt_response_code' => $receipt_response_code,
                'receipt_response_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
            ];
            CollectionApiRequest::where('id',$collection_id)->update($updateData);
            Log::debug('回执接口返回:' . json_encode($result,JSON_UNESCAPED_UNICODE));
        }
    }

    protected  function withholdingEvent(RepayRecord $recordInfo){
        //判断是否回执成功
        $collectionData = CollectionApiRequest::where('response_code',CollectionApiRequest::RESPONSE_OK)->where('apply_number',$recordInfo['apply_number'])->first();
        //判断是否回执成功了
        if($collectionData && $collectionData->status == CollectionApiRequest::STATUS_RECEIPT_OK){
            \Log::debug('接口回执:全部还清' . ":回执流水号为" . $recordInfo->apply_number . '的回执已经成功,不能重复回执' . Carbon::now()->toDateTimeString());
            $data=[
                'apply_number'=>$recordInfo->apply_number,
                'state'=>2,
                'message'=>'代扣失败,已经全部还清'
            ];
            return $data;

        }

        $api_type=0;
        if($recordInfo->repay_type==RepayRecord::REPAY_TYPE_WITHHOLDING){
            $api_type=self::NOTIFY_TYPE_ONE;

        }elseif($recordInfo->repay_type==RepayRecord::REPAY_TYPE_ACCOUNT){
            $api_type=self::NOTIFY_TYPE_TWO;
        }elseif($recordInfo->repay_type==RepayRecord::REPAY_TYPE_REPAYMENT){
            $api_type=self::NOTIFY_TYPE_THREE;
        }

        if($recordInfo->repay_type!=RepayRecord::REPAY_TYPE_REPAYMENT){
            $recordResult=RepayRecord::where('summary_id',$recordInfo->summary_id)
                ->where('apply_number',$recordInfo->apply_number)
                ->whereIn('status',[RepayRecord::STATUS_THREE,RepayRecord::STATUS_FOUR])->get();
            $repayCount=RepayRecord::where('summary_id',$recordInfo->summary_id)
                ->where('apply_number',$recordInfo->apply_number)
                ->where('status','!=',1)->count();

        }else{
            $recordResult=RepayRecord::where('summary_id',$recordInfo->summary_id)
                ->where('pay_off',RepayRecord::PAY_OFF_TWO)
                ->where('period','!=',0)
                ->get();
            ;
            $repayCount=RepayRecord::where('summary_id',$recordInfo->summary_id)
                ->where('pay_off',RepayRecord::PAY_OFF_TWO)->where('period','!=',0)->count()
            ;

        }

        \Log::debug(['全部执行与触发数据比较'=>$repayCount==count($recordResult)]);

        //todo 全部执行完毕执行通知逻辑
        if($repayCount==count($recordResult)){
            $recordIds=[];//事件通知
            $periods=[];//成功期限通知
            $message='';
            $partSuccessRecorIds=[];//todo 部分成功推送事件id
            foreach ($recordResult as $key => $record) {
                $feedBackList[] = [
                    'periodNumber' => $record->period,
                    'repayPlanNumber' => $record->relationSummary->data_type==\App\Models\RepaySummary::DATA_TYPE_TWO?$record->repay_plan_number:'K2-' . $record->id . '-' . date('Ymd', strtotime($record->created_at)),
                    'repayState' => $record->status == RepayRecord::STATUS_FOUR ? 1 : 2,
                    'repayMessage' => $record->status == RepayRecord::STATUS_FOUR ? '还款成功' : $record->failure_message,
                    // 'debtMoney'=>RepaySummary::getNotRepayAmount($record),
                ];
                if ($record->status == RepayRecord::STATUS_FOUR) {//
                    $periods[] = $record->period;
                    $recordIds[] = $record->id;
                } elseif ($record->status == RepayRecord::STATUS_THREE) {
                    $message = $record->failure_message;
                    //todo 部分成功记录推送
                    if ($record->money->status == RepayRecordMoney::STATUS_FOUR || $record->month->status == RepayRecordMonth::STATUS_FOUR || $record->common->status == RepayRecordCommon::STATUS_FOUR) {
                        $partSuccessRecorIds[] = $record->id;
                    }
                }
            }

            $pushRecordIds=array_merge($recordIds,$partSuccessRecorIds);
            if($pushRecordIds){//todo 如果存在成功的通知事件
                foreach($pushRecordIds as $key=>$pushRecordId){
                    $event=['summaries'=>$recordInfo->summary_id,'records'=>[$pushRecordId]];
                    event(new RepayMentEvent($recordInfo->summary_id));
                    event(new ActiveDeductionEvent($recordInfo->id));

                }
            }
            //todo  等推送对接//推送后结果
            $sendData=[];

            if(count($periods)==$repayCount){//todo 期限合计等于该期回款，推送成功
                $sendData=$this->sendData($recordInfo,$api_type,1);
            }else{//todo 失败或者部分失败
                if($partSuccessRecorIds){
                    $sendData=$this->sendData($recordInfo,$api_type,3);
                }else{
                    $sendData=$this->sendData($recordInfo,$api_type,2);
                }


            }
            $sendData['feedBackList']=$feedBackList;
            \Log::debug('代扣回执成功拉，数据'.(json_encode($sendData)));
            $result = \CollectionRequest::sendReceipt($sendData);
            \Log::debug('tets-tianping');
            $this->saveReceiptData($collectionData->id,$result);

        }
    }

    public function PayCompensateEvent(RepayRecord $recordInfo)
    {

        //判断是否回执成功
        $collectionData = CollectionApiRequest::where('response_code',CollectionApiRequest::RESPONSE_OK)->where('apply_number',$recordInfo['apply_number'])->first();
        //判断是否回执成功了
        if($collectionData && $collectionData->status == CollectionApiRequest::STATUS_RECEIPT_OK){
            \Log::debug('接口回执:销账' . ":回执流水号为" . $recordInfo->apply_number . '的回执已经成功,不能重复回执' . Carbon::now()->toDateTimeString());
            return;
        }
        $recordResult=RepayRecord::where('summary_id',$recordInfo->summary_id)
            ->where('apply_number',$recordInfo->apply_number)
            ->whereIn('status',[RepayRecord::STATUS_THREE,RepayRecord::STATUS_FOUR])->get();
        $repayCount=RepayRecord::where('summary_id',$recordInfo->summary_id)
            ->where('apply_number',$recordInfo->apply_number)
            ->where('status','!=',1)->count();

        if($repayCount==count($recordResult)){
            $recordIds=[];//事件通知
            $periods=[];//成功期限通知
            $partSuccessRecordIds=[];
            foreach($recordResult as $key=>$record){
                if($record->status==RepayRecord::STATUS_FOUR){//
                    $recordIds[]=$record->id;
                    $periods[]=$record->period;
                }elseif($record->status==RepayRecord::STATUS_THREE){
                    if($record->money->status==RepayRecordMoney::STATUS_FOUR || $record->month->status==RepayRecordMonth::STATUS_FOUR || $record->common->status==RepayRecordCommon::STATUS_FOUR){
                        $partSuccessRecordIds[]=$record->id;
                    }else{
                        $partFailRecordIds[]=$record->id;
                    }
                }
            }
            $pushRecordIds=array_merge($recordIds,$partSuccessRecordIds,$partFailRecordIds);
            if($pushRecordIds){
                foreach($pushRecordIds as $key=>$pushRecordId){
                    $event=['summaries'=>$recordInfo->summary_id,'records'=>[$pushRecordId]];


                    event(new RepayMentEvent($recordInfo->summary_id));
                    event(new ActiveDeductionEvent($recordInfo->id));

                }
            }
            if($recordInfo->status==\App\Models\RepayRecord::STATUS_FOUR){
                $sendData=$this->sendData($recordInfo,self::NOTIFY_TYPE_TWO,1);
            }elseif($recordInfo->status==\App\Models\RepayRecord::STATUS_THREE){
                $sendData=$this->sendData($recordInfo,self::NOTIFY_TYPE_TWO,2);
                if($periods){
                    $returnArray['period']=$periods;
                }
            }else{
                return ;
            }

            $result = \CollectionRequest::sendReceipt($sendData);
            $this->saveReceiptData($collectionData->id,$result);
        }
    }
}
